package top.laoshuzi.common.mvp.base;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import top.laoshuzi.common.mvp.factory.PresenterFactory;
import top.laoshuzi.common.mvp.factory.ReflectionPresenterFactory;
import top.laoshuzi.common.mvp.presenter.PresenterLifecycleDelegate;
import top.laoshuzi.common.mvp.view.View;

public class BaseMVPFrameLayout extends FrameLayout implements View {

    private PresenterLifecycleDelegate presenterDelegate = new PresenterLifecycleDelegate(ReflectionPresenterFactory.fromViewClass(this));

    public BaseMVPFrameLayout(Context context) {
        super(context);
    }

    public BaseMVPFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BaseMVPFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        presenterDelegate.create(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        presenterDelegate.destroy(!getActivity().isChangingConfigurations());
    }

    protected Activity getActivity() {
        Context context = getContext();
        while (!(context instanceof Activity) && context instanceof ContextWrapper)
            context = ((ContextWrapper) context).getBaseContext();
        if (!(context instanceof Activity))
            throw new IllegalStateException("Expected an activity context, got " + context.getClass().getSimpleName());
        return (Activity) context;
    }

    @Override
    public PresenterFactory getPresenterFactory() {
        return presenterDelegate.getPresenterFactory();
    }

    @Override
    public void setPresenterFactory(PresenterFactory presenterFactory) {
        presenterDelegate.setPresenterFactory(presenterFactory);
    }
}
